import { Inject, Injectable } from '@nestjs/common';
import { CreateCityDto } from './dto/create-city.dto';
import { UpdateCityDto } from './dto/update-city.dto';
import { City } from './entities/city.entity';
import { InjectEntityManager, InjectRepository } from '@nestjs/typeorm';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class CityService {
  @InjectEntityManager()
  private readonly entityManager;

  @InjectRepository(City)
  private readonly cityRepository;

  @Inject(ConfigService)
  private readonly configService;

  // /**
  //  * 向父级插入输入
  //  * @params createData
  //  * @params parentName
  //  */
  // createCity(createData: CreateCityDto, parentName: string | undefined){
  // }

  async create(createCityDto: CreateCityDto) {
    // const city = this.entityManager.create(City, createCityDto);
    const { parent, children, ...bodyContent } = createCityDto;

    let parentCity = null;
    if ((parent ?? '') !== '') {
      parentCity = await this.cityRepository.findOne({
        where: {
          name: parent,
        },
      });
    }

    const city = await this.cityRepository.save(bodyContent);

    if (children) {
      for (let i = 0; i < children.length; i++) {
        let child = await this.cityRepository.findOne({
          where: {
            name: children[i],
          },
        });
        if (!child) {
          child = await this.cityRepository.save({
            name: children[i],
            parent: city,
          });
        } else {
          city.children.push(child);
        }
      }
    }

    if (parentCity) {
      city.parent = parentCity;
      this.cityRepository.save(city);
    }

    // if(children){

    // }

    return await this.cityRepository.findTrees(city);
    // city.name = '华北';
    // await this.entityManager.save(city);

    // const cityChild = new City();
    // cityChild.name = '山东';

    // const parent = await this.entityManager.findOne(City, {
    //   where: {
    //     name: '华北',
    //   },
    // });
    // if (parent) {
    //   cityChild.parent = parent;
    // }
    // await this.entityManager.save(City, cityChild);

    // return this.entityManager.getTreeRepository(City).findTrees();
  }

  async findAll2() {
    return await this.cityRepository.findTrees();
  }
  async findAll() {
    console.log('========configService=========');
    console.log(this.configService);
    console.log(this.configService.get('auth'));
    const res = await this.cityRepository
      .createQueryBuilder('city')
      .leftJoinAndSelect('city.children', 'child')
      .leftJoinAndSelect('child.children', 'grandChild')
      .select([
        'city.id',
        'city.name',
        'child.id',
        'child.name',
        'grandChild.id',
        'grandChild.name',
      ])
      .where('city.parent IS NULL') // 获取顶级城市
      .getMany();

    // 递归转换城市数据
    const transformCity = (city: City) => {
      let childrenContent = [];
      if (city.children) {
        childrenContent = city.children.map((child) => transformCity(child));
      }
      return {
        id: city.id,
        name: city.name,
        children: childrenContent, // 递归处理子城市
      };
    };

    const result = res.map(transformCity);

    return result;
    // 只保留 children 的 name 属性，转换后的最终结构
    // const simplifyCityStructure = (city: any) => {
    //   return {
    //     id: city.id,
    //     name: city.name,
    //     children: city.children.map((child: any) => {
    //       return {
    //         id: child.id,
    //         name: child.name,
    //         children: child.children.map((grandChild: any) => grandChild.name),
    //       };
    //     }),
    //   };
    // };

    // const finalResult = result.map(simplifyCityStructure);

    // return finalResult;

    // .leftJoinAndSelect('city.children', 'children')
    // .leftJoinAndSelect('city.parent', 'parent')
    // .select([
    //   'city.name',
    //   'city.id',
    //   'parent.name',
    //   'children.id',
    //   'children.name',
    // ])
    // .getMany();
    // return res.map((item) => {
    //   return {
    //     ...item,
    //     parent: item?.parent?.name,
    //     children: item.children.map((child) => {
    //       return child?.name;
    //     }),
    //   };
    // });
  }

  findOne(id: number) {
    return `This action returns a #${id} city`;
  }

  update(id: number, updateCityDto: UpdateCityDto) {
    return `This action updates a #${id} city`;
  }

  remove(id: number) {
    return `This action removes a #${id} city`;
  }
}
